package middleware

import (
	"net/http"
	"time"

	"gitee.com/openeuler/uos-libvirtd-exporter/slogx"
)

type responseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (rw *responseWriter) WriteHeader(code int) {
	rw.statusCode = code
	rw.ResponseWriter.WriteHeader(code)
}

// HTTPMiddleware 是通用的 net/http 日志中间件
func HTTPMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}

		traceID := r.Header.Get("X-Trace-ID")
		ctx := slogx.WithTraceID(r.Context(), traceID)

		defer func() {
			if rec := recover(); rec != nil {
				slogx.ErrorCtx(ctx, "panic recovered", "err", rec)
				http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
			}

			duration := time.Since(start)
			slogx.InfoCtx(ctx, "http request",
				"method", r.Method,
				"path", r.URL.Path,
				"status", rw.statusCode,
				"remote", r.RemoteAddr,
				"duration_ms", duration.Milliseconds(),
				"user_agent", r.UserAgent(),
			)
		}()

		next.ServeHTTP(rw, r.WithContext(ctx))
	})
}
